package com.ruoyi.framework.web.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.common.core.redis.RedisCache;

/**
 * 注册服务实现
 * 
 * @author ruoyi
 */
@Service
public class SysRegisterService
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 注册
     */
    public String register(RegisterBody registerBody)
    {
        String msg = "";
        String username = registerBody.getUsername();
        String password = registerBody.getPassword();
        String code = registerBody.getCode();
        String uuid = registerBody.getUuid();
        String roleKey = registerBody.getRoleKey();

        // 验证码开关
        if (configService.selectCaptchaEnabled())
        {
            validateCaptcha(username, code, uuid);
        }

        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else
        {
            SysUser sysUser = new SysUser();
            sysUser.setUserName(username);
            if (!userService.checkUserNameUnique(sysUser))
            {
                msg = "注册用户'" + username + "'失败，登录账号已存在";
            }
            else
            {
                // 查询角色
                SysRole role = StringUtils.isNotEmpty(roleKey)
                        ? roleService.selectRoleByRoleKey(roleKey)
                        : null;

                // 如果roleKey为空或查不到，使用默认角色
                if (role == null)
                {
                    String defaultKey = configService.selectConfigByKey("sys.register.defaultRoleKey");
                    if (StringUtils.isEmpty(defaultKey))
                    {
                        defaultKey = "common";
                    }
                    role = roleService.selectRoleByRoleKey(defaultKey);
                }

                if (role == null || role.getRoleId() == null)
                {
                    msg = "无效的角色配置，请联系管理员";
                }
                else
                {
                    sysUser.setNickName(username);
                    sysUser.setPassword(SecurityUtils.encryptPassword(password));
                    
                    // 设置新增字段 - 后端统一处理，确保数据一致性
                    if ("yewuyuan".equals(roleKey) && StringUtils.isNotEmpty(registerBody.getEmployeeId())) {
                        // 业务员角色且有工号，设置employeeId
                    sysUser.setEmployeeId(registerBody.getEmployeeId());
                    sysUser.setLevel(registerBody.getLevel());
                        sysUser.setEe("正常");
                    } else {
                        // 非业务员角色或没有工号，设置为null
                        sysUser.setEmployeeId(null);
                        sysUser.setLevel(null);
                        sysUser.setEe(null);
                    }
                    
                    // 设置部门ID
                    if (registerBody.getDeptId() != null) {
                        sysUser.setDeptId(registerBody.getDeptId());
                    }
                    
                    // 添加调试日志
                    System.out.println("=== 注册调试信息 ===");
                    System.out.println("RegisterBody level: " + registerBody.getLevel());
                    System.out.println("RegisterBody employeeId: " + registerBody.getEmployeeId());
                    System.out.println("RegisterBody ee: " + registerBody.getEe());
                    System.out.println("RegisterBody deptId: " + registerBody.getDeptId());
                    System.out.println("SysUser level: " + sysUser.getLevel());
                    System.out.println("SysUser employeeId: " + sysUser.getEmployeeId());
                    System.out.println("SysUser ee: " + sysUser.getEe());
                    System.out.println("SysUser deptId: " + sysUser.getDeptId());
                    System.out.println("==================");
                    
                    // 设置角色
                    sysUser.setRoleIds(new Long[]{ role.getRoleId() });
                    
                    // 检查工号唯一性（包括已删除的用户）
                    if (StringUtils.isNotEmpty(sysUser.getEmployeeId())) {
                        SysUser existingUser = userService.checkEmployeeIdUniqueWithRecycle(sysUser.getEmployeeId());
                        if (existingUser != null) {
                            if ("2".equals(existingUser.getDelFlag())) {
                                // 工号被已删除的用户占用，物理删除该记录以释放工号
                                userService.deleteUserPhysically(existingUser.getUserId());
                            } else {
                                msg = "工号已存在，请使用其他工号";
                                return msg;
                            }
                        }
                    }
                    
                    try {
                        boolean regFlag = userService.registerUser(sysUser);
                        if (!regFlag)
                        {
                            msg = "注册失败,请联系系统管理人员";
                        }
                        else
                        {
                            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
                        }
                    } catch (Exception e) {
                        // 处理数据库约束异常
                        String errorMessage = e.getMessage();
                        if (errorMessage != null) {
                            if (errorMessage.contains("Duplicate entry") && errorMessage.contains("idx_employee_id")) {
                                msg = "工号已存在，请使用其他工号";
                            } else if (errorMessage.contains("Duplicate entry") && errorMessage.contains("user_name")) {
                                msg = "用户名已存在，请使用其他用户名";
                            } else if (errorMessage.contains("Duplicate entry")) {
                                msg = "信息重复，请检查输入内容";
                            } else if (errorMessage.contains("Error updating database")) {
                                msg = "数据库操作失败，请联系管理员";
                            } else {
                                msg = "注册失败：" + errorMessage;
                            }
                        } else {
                            msg = "注册失败，请重试";
                        }
                    }
                }
            }
        }
        return msg;
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }
}
